package org.cocos2dx.javascript.admob;

import android.app.Activity;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.Gravity;
import android.widget.FrameLayout;
import org.cocos2dx.javascript.admob.Ad_Fail_Timer;

import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.LoadAdError;
import com.logicgame.carmerge.R;

import androidx.annotation.NonNull;

public class Banner {
    //加载banner
    public static void InitBunnerAD(final Activity app){
        final String BANNER_AD_UNIT_ID = app.getString(R.string.BANNER_AD_UNIT_ID);
        final AdView adView = new AdView(app);
        AdSize adSize = getAdSize(app);
        adView.setAdSize(adSize);
        adView.setAdUnitId(BANNER_AD_UNIT_ID);
        AdRequest adRequest = new AdRequest.Builder().build();
        adView.loadAd(adRequest);
        adView.setAdListener(new AdListener() {
            @Override
            public void onAdFailedToLoad(@NonNull LoadAdError loadAdError) {
                super.onAdFailedToLoad(loadAdError);
                Ad_Fail_Timer.reload(1,app);
            }

            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                app.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if(adView.getParent() == null){
                            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
                            params.gravity = Gravity.BOTTOM;
                            app.addContentView(adView, params);
                        }else{  }
                    }
                });
            }
        });
        // TODO: Add adView to your view hierarchy.
    }
    private static AdSize getAdSize(Activity app) {
        // Step 2 - Determine the screen width (less decorations) to use for the ad width.
        Display display = app.getWindowManager().getDefaultDisplay();
        DisplayMetrics outMetrics = new DisplayMetrics();
        display.getMetrics(outMetrics);

        float widthPixels = outMetrics.widthPixels;
        float density = outMetrics.density;

        int adWidth = (int) (widthPixels / density);

        // Step 3 - Get adaptive ad size and return for setting on the ad view.
        return AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(app, adWidth);
    }
}
